﻿using Microsoft.Extensions.Configuration;
using Sale.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using SqlSugar;
using System.Data;
using DbType = SqlSugar.DbType;
using Sale.Domain;
using Sale.Domain.工单;

namespace Sale.Infrastructure.Implement
{
    public class DatabaseContext : IDatabaseContext
    {
        private readonly string _connectionString;
        public SqlSugarScope SqlSugar { get; }

        public SqlSugarScope SqlSugarScope => throw new NotImplementedException();

        public DatabaseContext(IConfiguration configuration)
        {
            _connectionString = configuration.GetValue<string>("erp");
            SqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = DbType.SqlServer,
                ConnectionString = _connectionString,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
            },
            db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
        }
        public void InitializeDatabase()
        {
            try
            {
                SqlSugar.CodeFirst.InitTables(
                    //typeof(ClientModel),
                    //typeof(ClientPriceModel),
                    //typeof(ContractModel),
                    //typeof(CTypeModel),
                    //typeof(LadderModel),
                    //typeof(RebuyModel),
                    //typeof(SalesOrderModel)
                    typeof(OpenFareModel)
                );

                Console.WriteLine("数据库表初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                throw;
            }
        }
    }
}
